package com.minshenglife.zanzan.web.weixin.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.minshenglife.zanzan.pub.message.WXRespMessage;
import com.minshenglife.zanzan.pub.message.custservice.GetAccessTokenMessage;
import com.minshenglife.zanzan.pub.utils.WXKeys;
import com.minshenglife.zanzan.web.service.RequestTaskService;
import com.minshenglife.zanzan.web.weixin.model.WXUserInfo;
import com.nationsky.pub.utils.GsonUtils;
import com.nationsky.pub.utils.StringUtils;

public class WXBaseService {
	static Logger log = LoggerFactory.getLogger(WXBaseService.class);
	
	/**
	 * 
	 * @param code
	 * @return
	 * @throws Exception 
	 */
	public static GetAccessTokenMessage getAccessTokenByCode(String code) throws Exception{
		String url =getAccessTokenByCodeUrl(code);
		log.debug(url);
		String json=RequestTaskService.sendDataStream(url, null);
		log.debug(json);
		try {
			GetAccessTokenMessage respMessage=GsonUtils.fromGson(json, GetAccessTokenMessage.class);
			return respMessage;
		} catch (Exception e) {
			e.printStackTrace();
			log.error(json);
			return null;
		}
	}
	
	/**
	 * 用户同意授权，获取code
	 * @param redirectUrl 回调地址
	 * @param isGetUserInfo 是否要获取用户详细信息，如果为false：则只能获取用户的openId
	 * scope:snsapi_userinfo 获取详细信息，scope:snsapi_base 只获取openId
	 * @param wechat_redirect 直接在微信打开链接，可以不填此参数。做页面302重定向时候，必须带此参数
	 * @param state 状态标识，可以是任意字符
	 * @return
	 * @throws Exception 
	 */
	public static void getCodeByAuthorize(String redirectUrl,boolean isGetUserInfo,String wechat_redirect
			,String state) throws Exception{
		String url =getCodeByAuthorizeUrl(redirectUrl,isGetUserInfo,wechat_redirect,state);
		log.debug(url);
		String json=RequestTaskService.sendDataStream(url, null);
		log.debug(json);
	}
	/**
	 * 发送微信客服消息
	 * @param obj 
	 * @throws Exception 
	 */
	public static WXRespMessage sendCustServiceMessage(Object obj,String token) throws Exception{
		WXRespMessage respMessage=null;
		log.debug("start sendCustServiceMessage() method");
//		String token=getWXAccessToken();
		String url=getSendCustServiceMessageUrl(token);
		log.debug(url);
		String con=GsonUtils.toGson(obj);
		log.debug(con);
		String json=RequestTaskService.sendDataStream(url, con);
		log.debug(json);
		respMessage=GsonUtils.fromGson(json, WXRespMessage.class);
		return respMessage;
	}
	
	/**
	 * 创建微信菜单
	 * @param obj
	 * @return
	 * @throws Exception
	 */
	public static WXRespMessage createMenu(Object obj,String token) throws Exception{
		WXRespMessage respMessage=null;
//		String token=getWXAccessToken();
		String url=getCreateMenuUrl(token);
		log.debug(url);
		String con=GsonUtils.toGson(obj);
		log.debug(con);
		con =con.replace("\\u003d", "=");
		log.debug(con);
		String json=RequestTaskService.sendDataStream(url, con);
		log.debug(json);
		respMessage=GsonUtils.fromGson(json, WXRespMessage.class);
		return respMessage;
	}
	/**
	 * 获取微信用户信息
	 * @param openid
	 * @return
	 * @throws Exception
	 */
	public static WXUserInfo getWXUserInfo(String openid,String token) throws Exception{
		WXUserInfo userInfo=null;
//		String token=getWXAccessToken();
		String url=getReqUserInfoUrl(token,openid);
		log.debug(url);
		String json=RequestTaskService.sendDataStream(url, null);
		userInfo=GsonUtils.fromGson(json, WXUserInfo.class);
		return userInfo;
	}
	/**
	 * 获取微信访问token
	 * @return
	 * @throws Exception
	 */
	public static String getWXAccessToken() throws Exception{
		String json=RequestTaskService.sendDataStream(getAccessTokenUrl(), null);
		log.debug("getWXAccessToken() :" +json);
		WXRespMessage resp=GsonUtils.fromGson(json, WXRespMessage.class);
		//请求出错
		if(resp.getErrcode()!=null && !"0".equals(resp.getErrcode())){
			log.debug("请求Access_Token时，出现异常：" +json);
			return null;
		}else{
			return resp.getAccess_token();
		}
		 
	}
	/**
	 * 通过code获取accesstoken的url
	 * @param code
	 * @return
	 */
	private static String getAccessTokenByCodeUrl(String code){
		String url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" +WXKeys.WX_APPID+
				"&secret=" +WXKeys.WX_SECRET+
				"&code=" +code+
				"&grant_type=authorization_code";
		return url;
	}
	
	/**
	 * 获取发送客户消息Url
	 * @param redirectUrl 回调地址
	 * @param isGetUserInfo 是否要获取用户详细信息，如果为false：则只能获取用户的openId
	 * scope:snsapi_userinfo 获取详细信息，scope:snsapi_base 只获取openId
	 * @param wechat_redirect 直接在微信打开链接，可以不填此参数。做页面302重定向时候，必须带此参数
	 * @param state 状态标识，可以是任意字符
	 * @return
	 */
	public static String getCodeByAuthorizeUrl(String redirectUrl,boolean isGetUserInfo,String wechat_redirect,String state){
		String scope=isGetUserInfo? "snsapi_userinfo"	: "snsapi_base" ;
		String url="https://open.weixin.qq.com/connect/oauth2/authorize?appid="+WXKeys.WX_APPID+
				"&redirect_uri="+redirectUrl+
				"&response_type=code" +
				"&scope=" +scope+
				"&state=" +state+"#wechat_redirect";
				if(!StringUtils.isNullOrEmpty(wechat_redirect))
					url+="="+wechat_redirect;
		return url;
	}
	
	/**
	 * 获取发送客户消息Url
	 * @param accessToken
	 * @return
	 */
	private static String getSendCustServiceMessageUrl(String accessToken){
		String url="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
		return url;
	}
		
	/**
	 * 获取微信信息url
	 * @param accessToken
	 * @param openId
	 * @return
	 */
	private static String getReqUserInfoUrl(String accessToken,String openId){
		String url="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+accessToken+"&openid="+openId;
		return url;
	}
	/**
	 * 创建微信菜单url
	 * @param accessToken
	 * @return
	 */
	private static String getCreateMenuUrl(String accessToken){
		String url="https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+accessToken;
		return url;
	}
	/**
	 * 获取AccessToken Url
	 * @return
	 */
	private  static String getAccessTokenUrl(){
		String url="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+WXKeys.WX_APPID+"&secret="+WXKeys.WX_SECRET;
		return url;
	}
}
